package com.example.tmapdemo;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

public class XmlPullParsing {

	public static InputStream xmlInputstream( String url ) throws ClientProtocolException, IOException {
		
		InputStream in = null;

		HttpResponse response = null;
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(url);
		
		response = client.execute( get );
		
		int statusCode = response.getStatusLine().getStatusCode();
		
		if( statusCode == 200 ) {
			in = response.getEntity().getContent();
		}
		else {
			
		}
		
		return in;
	}
	
	public static String[] parser( InputStream is ) {
		String [] coordinates = null;
		
		XmlPullParserFactory xppf = null;
		XmlPullParser xpp = null;		
		try {
			xppf = XmlPullParserFactory.newInstance();
			xpp = xppf.newPullParser();
			
			
			if( is != null ) {
				xpp.setInput( is, "UTF-8" );
				
				int event = xpp.getEventType();
				String tag = null;

				while( event != XmlPullParser.END_DOCUMENT ) {
					
					switch( event ) {
					
					case XmlPullParser.START_TAG:
						tag = xpp.getName().trim();
						break;
						
					case XmlPullParser.TEXT:

						if( "coordinates".equals(tag) ) {
							if( !"".equals( xpp.getText().trim() )) {
								System.out.println( "[" + xpp.getText() +"]");
								coordinates  = xpp.getText().split(",");
							}
						}
						break;
					}
					
					event = xpp.next();
				}
				
			}

		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return coordinates;
	}
}
